package com.wbs.realm;

import com.wbs.api.AdminApi;
import com.wbs.api.SellerApi;
import com.wbs.model.TbAdmin;
import com.wbs.model.TbSeller;
import com.wbs.userToken.UserEunm;
import com.wbs.userToken.UserToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author: 芝梦
 * @Description: 用于运营商或商家的登陆权限验证
 * @DateTime: 2024/1/26 14:35
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private AdminApi adminApi;

    @Autowired
    private SellerApi sellerApi;

    //权限认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    //身份认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1. 强转参数
//        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserToken token = (UserToken) authenticationToken;
        //获取当前用户身份 商家/运营商
        UserEunm flag = token.getUserEunm();
        if (flag.equals(UserEunm.ADMIN)) {
            //2. 校验用户名
            TbAdmin admin = adminApi.selectAdminByUsername(token.getUsername());
            if (admin == null) {
                return null;
            }
            //3. 校验密码
            SimpleAuthenticationInfo realm = new SimpleAuthenticationInfo(admin, admin.getPassword(), ByteSource.Util.bytes(admin.getSalt()), "AdminUserRealm");
            //登录认证
            return realm;
        }else if (flag.equals(UserEunm.SELLER)){
            //2. 校验用户名
            TbSeller seller = sellerApi.selectSellerBySellerId(token.getUsername());
            if (seller == null) {
                return null;
            }
            //3. 校验密码
            SimpleAuthenticationInfo realm = new SimpleAuthenticationInfo(seller, seller.getPassword(), ByteSource.Util.bytes(seller.getSalt()), "SellerUserRealm");
            //登录认证
            return realm;
        }

        return null;
    }
}
